<template>
  <div class="login">
    <el-form :model="userForm" :rules="rules" status-icon ref="ruleForm" label-width="100px">
      <el-form-item label="账号" prop="username">
        <el-input type="text" v-model="userForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="text" v-model="userForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="loading" :loading="loading" type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 导入混入
import loginMixin from '@/mixin/loginMixin'

export default {
  data() {
    return {
      loading: false,
      userForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '账号不能为空' },
          // 自定义验证规则实现规则定义
          { validator: this.validateUsername },
          // {type:'string',regexp://}
        ],
        password: [{ required: true, message: '密码不能为空' }, { validator: this.validatePassword }],
      },
    }
  },
  // 混入
  mixins: [loginMixin],
  methods: {
    /* // 自定义验证规则
    validateUsername(rule, value, callback) {
      if (/^\s+$/.test(value)) {
        callback(new Error('空能不能当用户名'))
      } else {
        callback()
      }
    }, */
    submitForm(formName) {
      this.loading = true
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          // 发送一个指令，让vuex中来完成所有的请求和数据保存
          let bool = await this.$store.dispatch('user/loginAction', this.userForm)
          if (bool) {
            this.$router.replace('/admin')
          } else {
            this.$message({
              message: '账号和密码不正确',
              type: 'error',
              duration: 1500,
              onClose: () => (this.loading = false),
            })
          }
        } else {
          this.$message({
            message: '账号和密码要填写正确',
            type: 'error',
            duration: 1500,
            onClose: () => (this.loading = false),
          })
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.login {
  width: 500px;
  margin: 150px auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 50px 10px;
}
</style>